package dao

import (
	"context"
	"errors"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"time"
)

// dao 是数据库存储 映射到数据库表

type UserDAO struct {
	db *gorm.DB
}

func NewUserDAO(db *gorm.DB) *UserDAO {
	return &UserDAO{
		db: db,
	}
}

var (
	ErrUserDuplicateEmail    = errors.New("邮箱已存在")
	ErrUserNotFound          = errors.New("用户名不存在")
	ErrInvalidUserOrPassword = errors.New("用户名或密码不正确")
)

// Insert 新增一条记录
func (ud *UserDAO) Insert(ctx context.Context, u User) error {
	now := time.Now().UnixMilli()
	u.Ctime = now
	u.Utime = now
	err := ud.db.WithContext(ctx).Create(&u).Error
	if me, ok := err.(*mysql.MySQLError); ok {
		const uniqueIndexErrNo uint16 = 1062
		if me.Number == uniqueIndexErrNo {
			return ErrUserDuplicateEmail
		}
	}

	return err
}

// FindByName 查询操作
func (ud *UserDAO) FindByName(ctx context.Context, username string) (User, error) {
	var u User
	err := ud.db.WithContext(ctx).Where("username = ?", username).First(&u).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return User{}, ErrUserNotFound
		}
		return User{}, errors.New("系统错误")
	}
	return u, nil
}

type User struct {
	Id       int64  `gorm:"primaryKey,autoIncrement"`
	Username string `gorm:"unique"` // 设置唯一索引
	Password string
	Ctime    int64
	Utime    int64
}
